package com.example.demo.common;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 *  加盐加密/加盐解密
 */
public class PasswordTools {
    public  static String encrypt(String password){
        //1.产生盐值
        String salt = UUID.randomUUID().toString().replace("-","");//去掉横杠 32位
        //2.使用盐值+明文密码 得到加密的密码
        String finalPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes());
        //3.将盐值和加密密码共同返回
        String dbPassword = salt+"$"+finalPassword;
        return dbPassword;

    }
    /*
        验证登录密码
     */
    public  static String encrypt(String password,String salt){
        //1.使用盐值+明文密码 得到加密的密码
        String finalPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes());
        //3.将盐值和加密密码共同返回
        String dbPassword = salt+"$"+finalPassword;
        return dbPassword;

    }
    /*
        password 用户登录输入的密码
        dbPassword 数据库存储的加密的密码
     */

    public static boolean decrypt(String password,String dbPassword){
        boolean result = false;
        //参数正确
        if (StringUtils.hasLength(password) && StringUtils.hasLength(dbPassword)
            && dbPassword.length() == 65 && dbPassword.contains("$")){
            //得到盐值
            String[] passwordArr = dbPassword.split("\\$");
            String salt = passwordArr[0];
            //得到加盐加密的密码
           // String finalPassword = passwordArr[1];
            //生成验证密码的加盐加密密码
           String checkPassword =  encrypt(password,salt);
           if (checkPassword.equals(dbPassword)){
               result = true;
           }
        }
        return result;
    }
    public static void main1(String[] args) {
        String password = "12345";
        String dbpas = encrypt(password);
        System.out.println(decrypt(password,dbpas));
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = "12345";
        String dbpas = bCryptPasswordEncoder.encode(password);
        System.out.println(bCryptPasswordEncoder.matches(password,dbpas));
    }
}
